<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <div class="basic-info">
      <h3 class="info-title">基本信息</h3>

      <div class="info-grid">
        <div class="info-row">
          <span class="info-label">工单号：</span>
          <span class="info-content">{{ formData.docNo }}</span>
        </div>
        <div class="info-row">
          <span class="info-label">单据日期：</span>
          <span class="info-content">{{ formData.docDate }}</span>
        </div>
        <div class="info-row">
          <span class="info-label">预计产量:</span>
          <span class="info-content">{{ formData.planQty }}</span>
        </div>
      </div>

      <div class="info-grid">
        <div class="info-row">
          <span class="info-label">产品品号:</span>
          <span class="info-content">{{ formData.itemCode }}</span>
        </div>
        <div class="info-row">
          <span class="info-label">产品规格：</span>

          <el-tooltip
            class="item"
            effect="dark"
            :content="formData.itemSpecification"
            placement="top-start"
          >
            <span class="info-content">{{ formData.itemSpecification }}</span>
          </el-tooltip>
        </div>
        <div class="info-row">
          <span class="info-label">BOM版次：</span>
          <el-tooltip
            class="item"
            effect="dark"
            :content="formData.bomVersionTimes"
            placement="top-start"
          >
            <span class="info-content">{{ formData.bomVersionTimes }}</span>
          </el-tooltip>
        </div>
      </div>

      <div class="info-grid">
        <div class="info-row">
          <span class="info-label">承诺交期：</span>
          <span class="info-content">{{
            formData.planShipDate ? formData.planShipDate : '--'
          }}</span>
        </div>

        <div class="info-row">
          <span class="info-label">图号：</span>
          <span class="info-content">
            {{ formData.drawingNo }}
            <!-- <a href="#" class="view-link">查看</a> -->
          </span>
        </div>
        <div class="info-row">
          <span class="info-label">工单备注</span>
          <el-tooltip class="item" effect="dark" :content="formData.remark" placement="top-start">
            <span class="info-content">{{ formData.remark ? formData.remark : '--' }}</span>
          </el-tooltip>
        </div>
      </div>
    </div>

    <el-tabs v-model="subTabsName" @tab-click="handleFClick">
      <el-tab-pane label="物料详情" name="workOrderBomPlc">
        <el-tabs v-model="activeName1" class="demo-tabs" @tab-click="handleClick1">
          <el-tab-pane
            :label="item.label"
            :name="item.label"
            v-for="item in getIntDictOptions(DICT_TYPE.OPTICORE_MATE_TYPE)"
            :key="item.value"
          >
            <WorkOrderBomPlcForm
              :tableList="tableList"
              :doc-no="formData.docNo"
              :selmaterialType="selmaterialType"
              :type="false"
            />
          </el-tab-pane>
        </el-tabs>
      </el-tab-pane>
      <el-tab-pane label="生产详情" name="collectedMaterials">
        <el-tabs v-model="activeName2" class="demo-tabs" @tab-click="handleClick2">
          <el-tab-pane
            :label="item.label"
            :name="item.label"
            v-for="item in getIntDictOptions(DICT_TYPE.OPTICORE_MATE_TYPE)"
            :key="item.value"
          >
            <WorkOrderBomPlcForm
              :tableList="tableList"
              :doc-no="formData.docNo"
              :selmaterialType="selmaterialType"
              :type="true"
              @update-data="updateData"
              @put-data="putData"
              @delete-data="deleteData"
            />
          </el-tab-pane>
        </el-tabs>
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <el-button @click="saveData" type="primary" :disabled="formLoading">保存</el-button>
      <!--      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>-->
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { MaterialApi } from '@/api/opticore/material'
import { MaterialUsageApi } from '@/api/opticore/materialusage'

import { WorkOrderCpsApi, WorkOrderCpsVO } from '@/api/opticore/workorder'
import WorkOrderBomPlcForm from './components/WorkOrderBomPlcForm.vue'
import type { TabsPaneContext } from 'element-plus'
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { update } from 'lodash-es'

/** 工单管理 表单 */
defineOptions({ name: 'WorkOrderCpsForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  docNo: undefined,
  docDate: undefined,
  itemCode: undefined,
  drawingNo: undefined,
  itemSpecification: undefined,
  bomVersionTimes: undefined,
  planQty: undefined,
  planShipDate: undefined,
  remark: undefined
})
const formRules = reactive({})
const formRef = ref() // 表单 Ref

/** 子表的表单 */
const subTabsName = ref('workOrderBomPlc')
const workOrderBomPlcFormRef = ref()

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  subTabsName.value = 'workOrderBomPlc'
  activeName1.value = getIntDictOptions(DICT_TYPE.OPTICORE_MATE_TYPE)[0].label
  getMaterialByDocNo(getIntDictOptions(DICT_TYPE.OPTICORE_MATE_TYPE)[0].value + '')
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await WorkOrderCpsApi.getWorkOrderCps(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 校验子表单
  try {
    await workOrderBomPlcFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'workOrderBomPlc'
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as WorkOrderCpsVO
    // 拼接子表的数据
    data.workOrderBomPlcs = workOrderBomPlcFormRef.value.getData()
    if (formType.value === 'create') {
      await WorkOrderCpsApi.createWorkOrderCps(data)
      message.success(t('common.createSuccess'))
    } else {
      await WorkOrderCpsApi.updateWorkOrderCps(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    docNo: undefined,
    docDate: undefined,
    itemCode: undefined,
    drawingNo: undefined,
    itemSpecification: undefined,
    bomVersionTimes: undefined,
    planQty: undefined,
    planShipDate: undefined,
    remark: undefined
  }
  formRef.value?.resetFields()
}

const activeName1 = ref(getIntDictOptions(DICT_TYPE.OPTICORE_MATE_TYPE)[0].label)
const activeName2 = ref(getIntDictOptions(DICT_TYPE.OPTICORE_MATE_TYPE)[0].label)

const handleClick1 = (tab: TabsPaneContext) => {
  let fItem = getIntDictOptions(DICT_TYPE.OPTICORE_MATE_TYPE).find(
    (item) => item.label == tab.props.name
  )
  getMaterialByDocNo(fItem.value + '')
}

const tableList = ref([])

const getMaterialByDocNo = async (materialType: string) => {
  tableList.value = await MaterialApi.getMaterialByDocNo(formData.value.docNo, materialType)
}

const updateData = (row: any) => {
  tableList.value.push(row)
  tableList.value = tableList.value.map((item) => {
    if (row.parentId == item.id) {
      return {
        ...item,
        isEditing: false
      }
    }

    return item
  })
}

const putData = (row: any) => {
  tableList.value = tableList.value.map((item) => {
    if (row.parentId == item.id) {
      let qtyVal

      if (row.qty <= item.qtyCopy) {
        qtyVal = item.qtyCopy - row.qty
      } else {
        qtyVal = 0
      }

      if (row.qty < 0) {
        qtyVal = item.qty
      }

      return {
        ...item,
        qty: qtyVal
      }
    }

    return item
  })
}

const deleteData = (row, index) => {
  tableList.value.splice(index, 1)
  tableList.value = tableList.value.map((item) => {
    if (row.parentId == item.id) {
      return {
        ...item,
        qty: item.qtyCopy,
        isEditing:true
      }
    }
    return item
  })
}

const selmaterialType = ref(null)

const handleClick2 = (tab: TabsPaneContext) => {
  let fItem = getIntDictOptions(DICT_TYPE.OPTICORE_MATE_TYPE).find(
    (item) => item.label == tab.props.name
  )
  selmaterialType.value = fItem.value + ''
  getMaterialUsageByDocNoList(fItem.value + '')
}

const getMaterialUsageByDocNoList = async (materialType: string) => {
  let res = await MaterialUsageApi.getMaterialUsageByDocNo(formData.value.docNo, materialType)

  tableList.value = res.map((item) => {
    return {
      ...item,
      readonly: true,
      qtyCopy: item.qty,
      isEditing: true
      // qtyCopy: item.qty-item-item.consumedQty,
    }
  })
}

const handleFClick = (tab: TabsPaneContext, event: Event) => {
  if (tab.props.name == 'workOrderBomPlc') {
    activeName1.value = getIntDictOptions(DICT_TYPE.OPTICORE_MATE_TYPE)[0].label
    getMaterialByDocNo(getIntDictOptions(DICT_TYPE.OPTICORE_MATE_TYPE)[0].value + '')
  } else if (tab.props.name == 'collectedMaterials') {
    activeName2.value = getIntDictOptions(DICT_TYPE.OPTICORE_MATE_TYPE)[0].label
    getMaterialUsageByDocNoList(getIntDictOptions(DICT_TYPE.OPTICORE_MATE_TYPE)[0].value + '')
  }
}

const findDuplicateSerialNos = (array) => {
  const serialNoCount = {}
  const duplicates = []

  for (const item of array) {
    const serialNo = item.serialNo
    serialNoCount[serialNo] = (serialNoCount[serialNo] || 0) + 1
  }

  for (const [serialNo, count] of Object.entries(serialNoCount)) {
    if (count > 1) {
      duplicates.push(serialNo)
    }
  }

  return duplicates
}

const saveData = async () => {
  // console.log(tableList.value)
  if (subTabsName.value == 'workOrderBomPlc') {
    dialogVisible.value = false
    return
  }

  if (findDuplicateSerialNos(tableList.value).length != 0) {
    message.error(`${findDuplicateSerialNos(tableList.value)}已存在`)
    return
  }

  // const fItem = tableList.value.find((item) => item.qty == 0)

  // if (fItem) {
    // message.error(`${fItem.serialNo}的数量不能为0`)
    // return
  // }

  const res = await MaterialApi.updateNewSerialNo(tableList.value)
  if (res) {
    dialogVisible.value = false
    message.success('保存成功！')
  }
}
</script>
<style scope>
.basic-info {
  font-family: Arial, sans-serif;
  padding: 20px;
  /* background-color: #f9f9f9; */
  border-radius: 8px;
}

.info-title {
  font-size: 18px;
  margin-bottom: 20px;
  color: #333;
}

.info-grid {
  display: flex;
  /* justify-content: space-between; */
  margin-bottom: 15px;
  border-bottom: 1px solid #eee;
  padding-bottom: 15px;
}

.info-row {
  /* flex: 1; */
  width: 33.3%;
  display: flex;
  margin-right: 10px;
}

.info-label {
  font-weight: bold;
  color: #666;
  min-width: 100px;
}

.info-content {
  color: #333;
  white-space: nowrap; /* 防止文字换行 */
  overflow: hidden; /* 文字溢出隐藏 */
  text-overflow: ellipsis; /* 出现省略号 */
}

.view-link {
  color: #1890ff;
  text-decoration: none;
  margin-left: 5px;
  cursor: pointer;
}

.other-info {
  margin-top: 15px;
}

.other-info .info-content {
  word-break: break-word;
}
</style>
